// 生成随机课程编号并确保唯一性
export async function generateUniqueCourseCode() {
    let courseCode;
    let isUnique = false;
    
    while (!isUnique) {
        // 生成课程编号
        courseCode = generateCourseCode();
        
        // 检查是否已存在
        const checkResponse = await fetch(`/check-course-code?courseCode=${courseCode}`);
        const checkData = await checkResponse.json();
        
        if (!checkData.exists) {
            isUnique = true;
        }
    }
    
    return courseCode;
}
export function generateCourseCode() {
    let randomNumber = '';
    // 第一位不为0
    randomNumber += Math.floor(Math.random() * 9) + 1; 
    for (let i = 0; i < 8; i++) {
        randomNumber += Math.floor(Math.random() * 10);
    }
    return `B${randomNumber}`;
}
// 创建课程
export async function createCourse() {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const response = await fetch(`/user-info?username=${username}`);
    const data = await response.json();
    //console.log('显示创建课程模态框');
    if (data.role === '教师') {
        const { user_id } = data;
        openModal('createCourseModal');
        document.getElementById('teacherUserId').value = user_id;
    } else {
        alert('该功能为教师专属，非教师无法使用');
    }
}

// 关闭创建课程模态框
export function closeCreateCourseModal() {
    document.getElementById('createCourseModal').style.display = 'none';
}

// 保存课程
export async function saveCourse() {
    const courseName = document.getElementById('courseName').value;
    const courseCode = await generateUniqueCourseCode();
    const syllabus = document.getElementById('syllabus').value;//25
    const teachingObjectives = document.getElementById('teachingObjectives').value;//25
    const assessmentMethod = document.getElementById('assessmentMethod').value;//25
    const teacherUserId = document.getElementById('teacherUserId').value;
    const credits = parseFloat(document.getElementById('credits').value);
    const study_period = parseInt(document.getElementById('study_period').value);
    const place = document.getElementById('place').value;//25
    const course_time = document.getElementById('course_time').value;
    const teach_weeks = document.getElementById('teach_weeks').value;
    const codeRegex = /^(?=.*[a-zA-Z])(?=.*\d).+$/;
    const timeRegex = /^([1-7])_([1-9]|1[0-4])-([1-9]|1[0-4])$/;
    const weeksRegex = /^(([1-9]|1[0-6])(?:-([1-9]|1[0-6]))?)(?:,(([1-9]|1[0-6])(?:-([1-9]|1[0-6]))?))*$/

    const isValidPlace = place.trim()!== '';
    const isValidCredits =!isNaN(credits) && credits >= 0.5 && credits <= 5 && (Number.isInteger(credits) || (credits - Math.floor(credits) === 0.5));
    const isValidStudyPeriod =!isNaN(study_period) && study_period > 0 && study_period <= 100;
    let isValidCourseTime = timeRegex.test(course_time);
    const parts = course_time.split('_');
    if (isValidCourseTime) {
        const [start, end] = parts[1].split('-');
        isValidCourseTime = parseInt(start) < parseInt(end);
    }
    const isValidTeachWeeks = weeksRegex.test(teach_weeks);

    if(courseName.length>25){
        alert('课程名称不能超过25个字符');
        return;
    }
            if(syllabus>100){
        alert('教学大纲不能超过100个字符');
        return;
    }
            if(teachingObjectives>25){
        alert('教学目标不能超过25个字符');
        return;
    }
            if(assessmentMethod>25){
        alert('考核方式不能超过25个字符');
        return;
    }
            if(place>25){
        alert('上课地点不能超过25个字符');
        return;
    }
    
    if (courseName && courseCode && syllabus && teachingObjectives && assessmentMethod && codeRegex.test(courseCode) &&
        isValidPlace && isValidCredits && isValidStudyPeriod && isValidCourseTime && isValidTeachWeeks) {
        const checkResponse = await fetch(`/check-course-code?courseCode=${courseCode}`);
        const checkData = await checkResponse.json();
        if (checkData.exists) {
            alert('课程已存在');
            return;
        }

        // 检查时间冲突
        const allCoursesResponse = await fetch('/get-courses');
        const allCourses = await allCoursesResponse.json();
        const newCourseDay = parseInt(parts[0]);
        const newCourseStart = parseInt(parts[1].split('-')[0]);
        const newCourseEnd = parseInt(parts[1].split('-')[1]);

        for (const course of allCourses) {
            const existingCourseParts = course.course_time.split('_');
            const existingCourseDay = parseInt(existingCourseParts[0]);
            const existingCourseStart = parseInt(existingCourseParts[1].split('-')[0]);
            const existingCourseEnd = parseInt(existingCourseParts[1].split('-')[1]);

            if (newCourseDay === existingCourseDay &&
                ((newCourseStart >= existingCourseStart && newCourseStart <= existingCourseEnd) ||
                    (newCourseEnd >= existingCourseStart && newCourseEnd <= existingCourseEnd) ||
                    (existingCourseStart >= newCourseStart && existingCourseStart <= newCourseEnd) ||
                    (existingCourseEnd >= newCourseStart && existingCourseEnd <= newCourseEnd))) {
                alert('课程时间冲突，请选择其他时间！');
                return;
            }
        }

        const responseSave = await fetch('/create-course', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                courseName,
                courseCode,
                syllabus,
                teachingObjectives,
                assessmentMethod,
                teacherUserId,
                credits,
                study_period,
                place,
                course_time,
                teach_weeks
            })
        });
        const result = await responseSave.json();
        alert(result.message);
        closeCreateCourseModal();
    } else {
        alert('课程信息不合法');
    }
}

// 查看课程
export async function viewCourses() {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        window.location.href = `/view-course.html?username=${username}`;
    } catch (error) {
        console.error('获取课程信息失败:', error);
        alert('获取课程信息失败，请稍后重试');
    }
}

document.addEventListener('DOMContentLoaded', () => {
    const element = document.getElementById('courseSearchInput');
    if (element) {
        element.addEventListener('click',searchCourses);
    }
});
export async function searchCourses() {
    const searchInput = document.getElementById('courseSearchInput').value.trim();
    const response = await fetch('/get-courses');
    const courses = await response.json();
    const courseList = document.getElementById('courseList');
    courseList.innerHTML = '';

    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();
    const isTeacher = userData.role === '教师';

    const filteredCourses = courses.filter(course => {
        return course.course_code.includes(searchInput);
    });
    if (filteredCourses.length === 0) {
        courseList.innerHTML = '<p class="no-content-message">暂无符合条件的课程</p>';
    }
    filteredCourses.forEach(course => {
        const courseBox = document.createElement('div');
        courseBox.classList.add('course-box');
        let buttonHtml = `
            <button onclick="openViewChaptersModal('${course.course_code}')">查看章节</button>
            <button onclick="new_openViewResourcesModal('${course.course_code}')">查看资源</button>
            <button onclick="openCoursePreviewModal('${course.course_code}')">课程预览</button>
        `;
        if (isTeacher) {
            buttonHtml += `
                <button onclick="checkRoleAndAddChapter('${course.course_code}', '${course.teacher_user_id}')">新增章节</button>
                <button onclick="checkRoleAndDeleteChapter('${course.course_code}', '${course.teacher_user_id}')">删除章节</button>
                <button onclick="openUploadResourceModal('${course.course_code}', '${course.teacher_user_id}')">上传资源</button>
            `;
        } else {
            buttonHtml += `
                <button onclick="selectCourse('${course.course_code}')">选择课程</button>
            `;
        }
        courseBox.innerHTML = `
            <h3>${course.course_code}——${course.course_name}</h3>
            <p><strong>任课教师：</strong> ${course.teacher_name}   <strong>上课时间：</strong> ${course.course_time}   <strong>上课地点：</strong>${course.place}</p>
            <p><strong>课程学分：</strong> ${course.credits}   <strong>课程学时：</strong> ${course.study_period}   <strong>考核方式：</strong>${course.assessment_method}</p>
            <p><strong>教学目标: </strong> ${course.teaching_objectives}</p>
            <p><strong>上课周次: </strong> ${course.teach_weeks}</p>
            <p style="color: #999; text-align: center;">(点击此处可以查看相关操作，再次点击收回)</p>
            <div class="course-buttons">
                ${buttonHtml}
            </div>
        `;
        courseBox.addEventListener('click', () => {
            const buttons = courseBox.querySelector('.course-buttons');
            if (buttons.style.display === 'none') {
                buttons.style.display = 'block';
            } else {
                buttons.style.display = 'none';
            }
        });
        courseList.appendChild(courseBox);
    });
}
// 在页面加载时检查用户角色，若为教师则显示“我创建的课程”按钮
/*document.addEventListener('DOMContentLoaded', async () => {
    startHeartbeat();
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        const response = await fetch(`/user-info?username=${username}`);
        const data = await response.json();
        if (data.role === '教师') {
            document.getElementById('viewMyCoursesButton').style.display = 'block';
        }
        console.log('read:',data);
        // 处理用户信息
        /*const usernameInput = document.getElementById('username');
        const nameInput = document.getElementById('name');
        const studentIdInput = document.getElementById('student_id');

        usernameInput.value = data.username;
        nameInput.value = data.name;
        studentIdInput.value = data.student_id;
    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
})*/

export function handleError(data, response) {
    if (response.status === 401 && (data.message === '用户未登录' || data.message === DIFFERENT_DEVICE_MSG)) {
        window.location.href = 'login.html';
    }
    throw new Error(data.message);
}

// 心跳机制
export function startHeartbeat() {
    setInterval(async () => {
        try {
            const response = await fetch('/heartbeat');
            if (!response.ok) {
                await handleError(response);
            }
        } catch (error) {
            console.error('心跳请求失败:', error);
        }
    }, 5000);
}

export function closeViewCoursesModal() {
    document.getElementById('viewCoursesModal').style.display = 'none';
}

export async function openCoursePreviewModal(courseCode) {
    try {
        // 获取课程详细信息
        const courseResponse = await fetch(`/get-course/${courseCode}`);
        const course = await courseResponse.json();

        // 获取课程对应的章节信息
        const chaptersResponse = await fetch(`/get-chapters?courseCode=${courseCode}`);
        const chapters = await chaptersResponse.json();

        const coursePreviewInfo = document.getElementById('coursePreviewInfo');
        coursePreviewInfo.innerHTML = `
            <div class="course-preview-header">
                <h3 class="text-2xl font-bold text-gray-800 mb-2">
                    <i class="fas fa-book-open mr-2 text-blue-500"></i>
                    ${course.course_code} - ${course.course_name}
                </h3>
                <div class="course-meta grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div class="meta-item flex items-center">
                        <i class="fas fa-user-tie mr-2 text-gray-600"></i>
                        <span><strong>教师:</strong> ${course.teacher_name}</span>
                    </div>
                    <div class="meta-item flex items-center">
                        <i class="fas fa-clipboard-check mr-2 text-gray-600"></i>
                        <span><strong>考核方式:</strong> ${course.assessment_method}</span>
                    </div>
                </div>
            </div>

            <div class="course-preview-content space-y-6">
                <div class="objective-section bg-blue-50 p-4 rounded-lg">
                    <h4 class="text-lg font-semibold text-blue-700 mb-2 flex items-center">
                        <i class="fas fa-bullseye mr-2"></i>教学目标
                    </h4>
                    <p class="text-gray-700 pl-6">${course.teaching_objectives}</p>
                </div>

                <div class="syllabus-section bg-gray-50 p-4 rounded-lg">
                    <h4 class="text-lg font-semibold text-gray-700 mb-2 flex items-center">
                        <i class="fas fa-map mr-2"></i>课程大纲
                    </h4>
                    <p class="text-gray-700 pl-6">${course.syllabus}</p>
                </div>

                <div class="chapters-section">
                    <h4 class="text-xl font-semibold text-gray-800 mb-4 border-b pb-2 flex items-center">
                        <i class="fas fa-list-ol mr-2"></i>课程章节
                    </h4>
                    ${chapters.length > 0 ? `
                        <ul class="space-y-3 chapter-list">
                            ${chapters.map(chapter => `
                                <li class="chapter-item bg-white p-3 rounded-lg shadow-sm hover:shadow-md transition-shadow">
                                    <div class="flex items-start">
                                        <span class="chapter-order bg-blue-100 text-blue-800 px-2 py-1 rounded-full text-sm font-medium mr-3">
                                            第${chapter.chapter_order + 1}章
                                        </span>
                                        <div>
                                            <h5 class="font-medium text-gray-800">${chapter.chapter_title}</h5>
                                            <p class="text-gray-600 mt-1">${chapter.chapter_content}</p>
                                        </div>
                                    </div>
                                </li>
                            `).join('')}
                        </ul>
                    ` : '<p class="text-gray-500 italic">暂无章节信息</p>'}
                </div>
            </div>
        `;

        document.getElementById('coursePreviewModal').style.display = 'block';
    } catch (error) {
        console.error('获取课程信息失败:', error);
        alert('获取课程信息失败，请稍后重试');
    }
}

export function closeCoursePreviewModal() {
    document.getElementById('coursePreviewModal').style.display = 'none';
}

// 打开选择课程模态框
export function openSelectCourseModal() {
    document.getElementById('selectCourseModal').style.display = 'block';
}

// 关闭选择课程模态框
export function closeSelectCourseModal() {
    document.getElementById('selectCourseModal').style.display = 'none';
}

// 选择课程
export async function selectCourse(courseCode) {
    // 检查课程是否存在
    const checkResponse = await fetch(`/check-course-code?courseCode=${courseCode}`);
    const checkData = await checkResponse.json();
    if (!checkData.exists) {
        alert('课程不存在');
        return;
    }

    // 获取所有已选课程
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const selectedCoursesResponse = await fetch(`/get-selected-courses?username=${username}`);
    if (!selectedCoursesResponse.ok) {
        alert('获取已选课程信息失败，请稍后重试');
        return;
    }
    const selectedCourses = await selectedCoursesResponse.json();

    // 检查学生是否已经选择该课程
    const isCourseSelected = selectedCourses.some(course => course.course_code === courseCode);
    if (isCourseSelected) {
        alert('你已经选择了该课程');
        return;
    }

    // 获取要选择的课程信息
    const courseResponse = await fetch(`/get-course/${courseCode}`);
    const course = await courseResponse.json();

    // 检查时间冲突
    const newCourseDay = parseInt(course.course_time.split('_')[0]);
    const newCourseStart = parseInt(course.course_time.split('_')[1].split('-')[0]);
    const newCourseEnd = parseInt(course.course_time.split('_')[1].split('-')[1]);

    for (const selectedCourse of selectedCourses) {
        const existingCourseDay = parseInt(selectedCourse.course_time.split('_')[0]);
        const existingCourseStart = parseInt(selectedCourse.course_time.split('_')[1].split('-')[0]);
        const existingCourseEnd = parseInt(selectedCourse.course_time.split('_')[1].split('-')[1]);

        if (newCourseDay === existingCourseDay &&
            ((newCourseStart >= existingCourseStart && newCourseStart <= existingCourseEnd) ||
                (newCourseEnd >= existingCourseStart && newCourseEnd <= existingCourseEnd) ||
                (existingCourseStart >= newCourseStart && existingCourseStart <= newCourseEnd) ||
                (existingCourseEnd >= newCourseStart && existingCourseEnd <= newCourseEnd))) {
            alert('课程时间冲突');
            return;
        }
    }

    // 选课成功，将选课信息保存到数据库
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();
    const studentId = userData.user_id;

    const response = await fetch('/select-course', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            student_id: studentId,
            course_code: courseCode
        })
    });
    const result = await response.json();
    alert(result.message);
}

export async function viewCourseSchedule() {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();

    if (userData.role === '教师') {
        alert('你无法使用该功能');
    } else {
        window.location.href = 'schedule.html?username=' + username;
    }
}

//退选课程
export async function dropCourse(courseCode) {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();
    const studentId = userData.user_id;

    const response = await fetch('/drop-course', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            student_id: studentId,
            course_code: courseCode
        })
    });
    const result = await response.json();
    alert(result.message);
    // 刷新课程列表
    viewCourses();
}

// 临时禁用过渡效果，直接显示模态框
export function openModal(modalId
) {
    //console.log('openModal', modalId);
  const modal = document.getElementById
(modalId);
  if (!modal) return
;
  
  // 移除所有初始状态类
  modal.
classList.remove("opacity-0", "pointer-events-none"
);
  
  // 设置显示属性
  modal.
style.display = 'flex'
;
  
  // 强制重绘确保过渡生效
  void modal.offsetHeight
;
  
  // 添加激活状态类
  modal.
classList.add("opacity-100", "pointer-events-auto"
);
  
  // 特殊处理内容层（关键修复）
  const content = modal.querySelector('.modal-content'
);
  if
 (content) {
    content.
classList.remove("scale-95", "opacity-0"
);
    content.
classList.add("scale-100", "opacity-100"
);
  }
}